package cn.xiaozhu.service.spring;
import cn.xiaozhu.dao.IFileMapper;
import cn.xiaozhu.entity.Resume;
import cn.xiaozhu.service.facade.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * 文件服务类
 */
@Service
public class FileService implements IFileService {
    private final static Logger logger = LoggerFactory.getLogger(FileService.class);
    /**
     * 访问dao层
     */
    @Autowired
    private IFileMapper fileMapper;
    /**
     * 获取.properties中文件上传下载路径
     */
    @Value("${uploadDir}")
    private String uploadDir;

    /**
     * 文件上传
     * originalName:文件原始名
     * suffixName:文件后缀名
     * filePath:文件路径
     * fileName:文件重新命名（数据库存放文件名）
     * realPath:文件真实路径
     * @param document
     * @param Id
     * @return
     */
    @Transactional(rollbackFor=IOException.class)
    @Override
    public boolean upload(MultipartFile document, Integer Id) {
        if (!document.isEmpty()) {
            String originalName = document.getOriginalFilename();
            String suffixName = originalName.substring(originalName.lastIndexOf("."));
            String filepath = uploadDir;
            String fileName = UUID.randomUUID() + suffixName;
            String realPath = filepath + fileName;
            File dest = new File(realPath);
            if (!dest.exists()) {
                dest.mkdirs();
            }
            try {
                fileMapper.addFile(Id, realPath, originalName);
                document.transferTo(dest);
            } catch (IOException e) {
                logger.info("上传失败");
            }
        } else {
            logger.info("文件为空");
            return false;
        }
        return true;
    }





    /**
     * 文件下载
     * @param fileName
     * @param request
     * @param response
     * @return
     * @throws IOException
     */

    @Override
    public boolean download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileUrl = uploadDir + fileName;
        File file = new File(fileUrl);
        if (file.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                logger.info("下载完成");
                return true;
            } catch (FileNotFoundException e) {
                logger.info("文件找不到");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        logger.info("关闭异常");
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        logger.error("关闭异常");
                    }
                }
            }
        }
        return false;
    }




    /**
     * 文件查找（根据用户Id查找）
     * @param Id
     * @return
     */
    @Override
    public List<cn.xiaozhu.entity.Resume> findAllFiles(Integer Id) {
        return fileMapper.getFileList(Id);
    }





    /**
     * 删除文件
     * document:根据文件Id查找到对应Resume文件，进而调用实体类Resume中的getRealPath()方法获取文件地址realPath
     * realPath:获取文件地址RealPath,进而通过realPath创建文件对象
     * 调用File的exists(),delete()等方法进行删除文件
     * @param fileId
     * @return
     */

    @Override
    public boolean delFileByFileId(Integer fileId) {

        if (!StringUtils.isEmpty(fileId)) {
            Resume document = fileMapper.getFileByFileId(fileId);
            String realPath = document.getRealPath();
            File file = new File(realPath);
            if (!file.exists()) {
                logger.info("文件不存在");
            } else {
                  file.delete();
            }
        } else{
            return false;
        }
        return fileMapper.delFileByFileId(fileId);
    }
}



